package com.byapp.fast.common.validator;

import com.byapp.fast.common.enums.ResultEnum;
import com.byapp.fast.common.exception.BYException;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

@Slf4j
public class ValidatorUtils {

    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     */
    public static void validateEntity(Object object, Class<?>... groups)
            throws BYException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            StringBuilder msg = new StringBuilder();
            for (ConstraintViolation<Object> constraint : constraintViolations) {
                msg.append(constraint.getMessage()).append("||");
            }
            log.error("【参数校验】校验失败，消息={}", msg.toString());
            throw new BYException(ResultEnum.ILLEGAL_PARAM);
        }
    }

}
